import React, { useState, useRef, forwardRef, useEffect } from 'react';
import { Button, message } from 'antd';
import { connect } from 'dva';
import BaseInfo from '../baseInfo';
import DeviceMessage from 'components/common/deviceMessage';
import MaintenanceMessage from 'components/common/maintenanceMessage';
import PreviewPlanModal from 'components/common/previewPlanModal';
import moment from 'moment';
import { updateCali, addList } from 'service/actions/deviceCali';
import router from 'umi/router';
import withRouter from 'umi/withRouter';
import KeepAlive from 'react-activation';
import './index.styl';

const BaseInfoRef = forwardRef((props, ref) => <BaseInfo {...props} cRef={ref} />);
const DeviceMessageRef = forwardRef((props, ref) => <DeviceMessage {...props} cRef={ref} />);
const MaintenanceMessageRef = forwardRef((props, ref) => (
  <MaintenanceMessage {...props} cRef={ref} />
));

function Plan({
  dispatch,
  id,
  location,
  dictionaryList: { deviceList, userList },
  deviceCali: { detail },
  headerTaps: { panes },
  commonAction: { catchObj }
}) {
  const [useObj, setUserObj] = useState({});
  const [deviceDetail, setDeviceDetail] = useState({});
  const baseInfoRef = useRef();
  const deviceMessageRef = useRef();
  const maintenanceMessageRef = useRef();
  useEffect(() => {
    // 编辑信息
    if (id !== undefined) {
      dispatch({
        type: 'deviceCali/getDetail',
        payload: { id },
      });
    }
  }, [dispatch, id]);
  useEffect(() => {
    dispatch({
      type: 'dictionaryList/getDeviceList',
      payload: {
        deviceName: '',
      },
    });
  }, [dispatch])

  useEffect(() => {
    dispatch({
      type: 'dictionaryList/getUserList',
      payload: {
        type: 5,
        current: 1,
        size: 999
      },
    });
  }, [dispatch])
  // 编辑的时候获取的详情信息 设备检定员信息  和  设备信息
  useEffect(() => {
    if (id) {
      setUserObj(detail && detail.userVo)
      setDeviceDetail(detail && detail.deviceVo)
    } else {
      setUserObj({});
      setDeviceDetail({});
    }
  }, [id, dispatch, detail])
  // 选择设备函数
  async function selectDevice(n, v) {
    const res = await dispatch({
      type: 'dictionaryList/getDeviceDetail',
      payload: {
        id: v,
      },
    });
    if (res.code === '000000') {
      setDeviceDetail(res.data)
    }

  }
  // 选择人员
  function selectPerson(v, id) {
    const userObj = userList.find(item => item.id.toString() === id);
    setUserObj(userObj);
  }
  // 提交预览
  async function submitData(userInfo, deviceInfo, planInfo, status) {
    baseInfoRef.current.validateFields();
    deviceMessageRef.current.validateFields();
    maintenanceMessageRef.current.validateFields();
    const Obj = {
      id,
      status,
      name: planInfo.name,
      remark: planInfo.remark,
      assayUser: userInfo && userInfo.id,
      deviceId: deviceInfo.id,
      startTime: planInfo.time ? moment(planInfo.time[0]).format('YYYY-MM-DD') + ' 00:00:00' : null,
      endTime: planInfo.time ? moment(planInfo.time[1]).format('YYYY-MM-DD') + ' 23:59:59' : null,
    };

    if (status === undefined) {
      const flag = (planInfo.name === '') || !Obj.startTime || !Obj.endTime || (userInfo.id === undefined) || (deviceInfo && deviceInfo.id === undefined) || (Obj.remark && Obj.remark.length > 50)
      if (flag) {
        return
      }
      dispatch({
        type: 'preview/updateIsshow',
        payload: { isShow: true },
      })
    } else {
      if (status === 5) {
        const flag = (planInfo.name === '') || (planInfo.time && planInfo.time.length === 0) || (userInfo.id === undefined) || (deviceInfo && deviceInfo.id === undefined) || (Obj.remark && Obj.remark.length > 50)
        if (flag) {
          return
        }
      }
      try {
        let data;
        if (id) {
          data = await updateCali({
            ...Obj
          })
        } else {
          data = await addList({
            ...Obj
          })
        }
        dispatch({
          type: 'preview/updateIsshow',
          payload: { isShow: false },
        });
        if (data.code === '050000' || data.code === '000000') {
          if (data.code === '000000') {
            message.success(data.mesg)
            handleCancle()
            return
          }
          message.error(data.mesg)
          handleCancle()
        } else {
          message.error(data.mesg)
        }
      } catch (error) {
        console.log(error)
      }
    }
  }
  // 提交完毕关闭页面
  function handleCancle() {
    const { pathname } = location
    const panesList = panes.filter(pane => pane.key !== pathname);
    dispatch({
      type: 'headerTaps/updateHeaderTaps',
      payload: { panes: panesList },
    });
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          'deviceCali_add': [false, true],
          'deviceCali_edit': [false, true]
        }
      }
    })
    dispatch({
      type: 'deviceCali/updateSerachParams',
      payload: {
        serachParams: {
          current: 1
        }
      }
    })
    router.push({
      pathname: '/deviceCali',
      params: { isRefresh: true }
    })
  }
  // 取消按钮直接返回上个页面
  function cancelLink() {
    const { pathname } = location
    const panesList = panes.filter(pane => pane.key !== pathname);
    if (panesList.length === 0) {
      return
    }
    let prevObj = {}
    panes.forEach((item, index) => {
      if (item.key === pathname) {
        if (index) {
          prevObj = panes[index - 1]
        } else {
          prevObj = panes[index + 1]
        }
      }
    })
    dispatch({
      type: 'headerTaps/updateHeaderTaps',
      payload: { panes: panesList },
    });
    dispatch({
      type: 'commonAction/uploadCatch',
      payload: {
        catchObj: {
          'deviceCali_add': [false, true],
          'deviceCali_edit': [false, true]
        }
      }
    })
    router.push({
      pathname: prevObj.path,
      query: prevObj.query
    })
  }
  return (
    <>
      <div className="AddCalibration">
        <BaseInfoRef ref={baseInfoRef} detail={detail} id={id} />
        <DeviceMessageRef
          show
          ref={deviceMessageRef}
          title='配置检定设备'
          defaultVal={id && detail && detail.deviceVo && detail.deviceVo.deviceName || ''}
          deviceList={deviceList}
          deviceInfo={deviceDetail}
          handleSelect={selectDevice}
        />
        <MaintenanceMessageRef
          show
          ref={maintenanceMessageRef}
          defaultVal={id && detail && detail.userVo && detail.userVo.name + detail.userVo.groupName || ''}
          userList={userList}
          maintenanceInfo={useObj}
          handleSelect={selectPerson}
          title="配置检定员"
          person="检定员"
          tipPerson="设备管理员"
        />
      </div>

      <div className="btnGroup">
        <Button className="preview" onClick={() => submitData(useObj, deviceDetail, baseInfoRef.current.values)}>
          提交预览
        </Button>
        {
          id ? (detail.status === 5 ? (<Button
            type="primary"
            onClick={() => submitData(useObj, deviceDetail, baseInfoRef.current.values, 5)}
          >
            存草稿
          </Button>) : null) : <Button
            type="primary"
            onClick={() => submitData(useObj, deviceDetail, baseInfoRef.current.values, 5)}
          >
              存草稿
          </Button>
        }
        <Button onClick={cancelLink}>取消</Button>
      </div>
      {/* 预览框 */}
      <KeepAlive when={catchObj.previewModal}>
        <PreviewPlanModal
          basicTitle="计划基本信息"
          deviceTitle="设备信息"
          userTitle="检定员信息"
          isCheckUser
          userInfo={useObj}
          deviceInfo={deviceDetail}
          planInfo={baseInfoRef.current && baseInfoRef.current.values}
          addList={() => submitData(useObj, deviceDetail, baseInfoRef.current.values, 1)}
        />
      </KeepAlive>
    </>
  );
}

export default connect(({ preview, dictionaryList, deviceCali, headerTaps, commonAction }) => ({
  preview,
  deviceCali,
  dictionaryList,
  headerTaps,
  commonAction
}))(withRouter(Plan));
